<template>
  <CompOperate
    :field="field"
    :designer="designer"
    :design-state="designState"
    :parent-list="parentList"
    :parent-widget="parentWidget"
    :sub-form-row-id="subFormRowId"
    :sub-form-row-index="subFormRowIndex"
    :sub-form-col-index="subFormColIndex"
    :index-of-parent-list="indexOfParentList"
    :display-style="field['options'].displayStyle"
  >
    <div class="scene-waiting-patient-widget" :style="setStyle('area')">
      <div class="scene-waiting-patient-inside">
        <div class="patient-area">
          <template v-for="(patientsItem, row) in getWaitingPatient">
            <div class="patient-group">
              <template v-for="(item, index) in patientsItem">
                <div class="patient-info" :style="setStyle('list')">
                  <div class="patient-info-inside">
                    <template v-if="item.patientName">
                      {{ patientNumberInfo(item, row, index) }}
                    </template>
                    {{ item.patientName || "\u00a0" }}
                  </div>
                </div>
              </template>
            </div>
          </template>
        </div>
      </div>
    </div>
  </CompOperate>
</template>

<script>
import { v4 as uuid } from "uuid";
import { pxToVw } from "@/utils/common";
import emitter from "@/utils/designer/emitter";
import { buildParentApi } from "@/utils/designer/util";
import mixin from "@sc/templateDetails/modules/homeMiddle/fieldMixin";
import CompOperate from "@c/public/form-designer/devType/modules/compOperate.vue";

let buildParent = buildParentApi();
export default {
  name: "scene-waiting-patients-widget",

  componentName: "FieldWidget", //必须固定为FieldWidget，用于接收父级组件的broadcast事件

  mixins: [emitter, mixin],

  components: {
    CompOperate,
  },

  props: {
    field: Object,
    widget: Object,
    designer: Object,
    parentList: Array,
    parentWidget: Object,
    indexOfParentList: Number,
    devType: {
      type: Boolean,
      default: () => {
        return false;
      },
    },
    designState: {
      type: Boolean,
      default: false,
    },
    /* 子表单组件行索引，从0开始计数 */
    subFormRowIndex: {
      type: Number,
      default: -1,
    },
    /* 子表单组件列索引，从0开始计数 */
    subFormColIndex: {
      type: Number,
      default: -1,
    },
    /* 子表单组件行Id，唯一id且不可变 */
    subFormRowId: {
      type: String,
      default: "",
    },
  },

  data() {
    return {
      widgetKey: uuid(),
      optionsInfo: Object(),
      fieldOptionsInfo: Object(),
      waitIndex: 0,
      timer: null,
      totalArr: [],
    };
  },

  computed: {
    // 模板的行内样式
    setStyle() {
      return function (val) {
        const self = this;
        let {
          contentHeight,
          headerColor,
          headerFontSize,
          headerBackground,
          headerFontWeight,
          listColor,
          listFontSize,
          listFontWeight,
        } = self.optionsInfo || Object();
        let Obj = Object();
        switch (val) {
          case "area":
            Reflect.set(Obj, "height", pxToVw(contentHeight));
            Reflect.set(Obj, "background", headerBackground);
            Reflect.set(Obj, "fontSize", pxToVw(headerFontSize));
            Reflect.set(Obj, "fontWeight", headerFontWeight);
            Reflect.set(Obj, "color", headerColor);
            return Obj;
          case "list":
            Reflect.set(Obj, "fontSize", pxToVw(listFontSize));
            Reflect.set(Obj, "fontWeight", listFontWeight);
            Reflect.set(Obj, "color", listColor);
            return Obj;
          case "patient":
            return Obj;
          case "listItem":
            return Obj;
        }
      };
    },

    //患者号的排序显示
    patientNumberInfo() {
      return function (row, index, key) {
        let { patientNumber = "2", col } = this.optionsInfo;
        switch (patientNumber) {
          case "1":
            return "\u00a0";
          case "2":
            return row.orderNo || "\u00a0";
          case "3":
            return index * col + 1 + key;
          default:
            return row.orderNo || "\u00a0";
        }
      };
    },

    //获取当前队列的候诊患者
    getWaitingPatient() {
      try {
    // 1. 获取基础配置
    const { row = 7, col = 4 } = this.optionsInfo;
    const total = row * col || 28;

    // 2. 获取患者列表数据
    const waitingPatientList = this.$store.getters["getWaitingPatientInfo"];
    const patientList = this.devType 
      ? (waitingPatientList?.apiData || [])
      : (waitingPatientList?.mockData || []);

    // 3. 获取并扁平化患者数据
    const ranksInfo = patientList.slice(0, 1);
    const flattenArr = this.$lodash.flattenDeep(
      this.$lodash.map(ranksInfo, "waitPatientList")
    );

    // 4. 更新分页数据
    this.totalArr = this.$lodash.chunk(flattenArr, total);
    this.waitIndex = this.totalArr.length <= 1 ? 0 : this.waitIndex;

    // 5. 处理数据返回
    const length = flattenArr?.length || 0;
    
    if (total > length) {
      // 处理数据不足一页的情况
      const fillArr = new Array(total - length).fill({});
      return this.$lodash.chunk([...flattenArr, ...fillArr], col);
    } else {
      // 处理分页数据
      const currentPage = this.totalArr[this.waitIndex] || [];
      const fillArr = new Array(total - currentPage.length).fill({});
      return this.$lodash.chunk([...currentPage, ...fillArr], col);
    }

  } catch (error) {
    console.error('获取等待患者列表失败:', error);
    // 返回空网格数据
    return Array(this.optionsInfo.row || 7)
      .fill()
      .map(() => Array(this.optionsInfo.col || 4).fill({}));
  }
      // let patientList = Array();
      // let devType = this.devType;
      // let { row = 7, col = 4 } = this.optionsInfo;
      // let waitingPatientList = this.$store.getters["getWaitingPatientInfo"];
      // if (devType) {
      //   patientList = waitingPatientList.apiData || Array();
      // } else {
      //   patientList = waitingPatientList.mockData || Array();
      // }
      // console.log(patientList, "patientList");
      // // 截取一个队列
      // let ranksInfo = patientList.slice(0, 1);
      // let summary = this.$lodash.map(ranksInfo, "waitPatientList");
      // let flattenArr = this.$lodash.flattenDeep(summary);
      // console.log(flattenArr, "flattenArr");

      // let total = row * col || 28;
      // console.log(this.$lodash.chunk(flattenArr, total));
      // this.totalArr = this.$lodash.chunk(flattenArr, total);
      // if (this.totalArr.length <= 1) {
      //   this.waitIndex = 0;
      // }
      // let length = flattenArr?.length || 0;
      // if (total > length) {
      //   let fillArr = new Array(total - length).fill({});
      //   let mergeArr = [...flattenArr, ...fillArr];
      //   return this.$lodash.chunk(mergeArr, col);
      // } else {
      //   let chunkArr = this.$lodash.chunk(flattenArr, total);
      //   let hasLength = chunkArr[this.waitIndex]?.length || 0;
      //   let fillArr2 = new Array(total - hasLength).fill({});
      //   let mergeArr2 = [...chunkArr[this.waitIndex], ...fillArr2];
      //   console.log(mergeArr2, this.$lodash.chunk(mergeArr2, col));
      //   return this.$lodash.chunk(mergeArr2, col);
      // }
    },
  },

  created() {
    this.registerToRefList();
    this.initEventHandler();
    this.handleOnCreated();
    if (this.optionsInfo.switchScreen) {
      this.startTimer();
    }
  },

  mounted() {
    console.log(this.getWaitingPatient, "getWaitingPatient");

  },

  methods: {
    // 接收父组件传递过来的数据
    async executeMethod(key, data) {
      switch (key) {
        case "patientListInfo":
          // console.log(`患者列表-数据处理逻辑-${JSON.stringify(data)}`);
          this.uuid = uuid();
          if (data.length === 0) {
            this.waitIndex = 0;
            this.totalArr = [];
            if (this.optionsInfo.switchScreen) {
              this.startTimer();
            }
          }
          let patientList = this.$lodash.cloneDeep(data);
          buildParent.executeParentMethod(
            "writeLog",
            JSON.stringify({ sign: "模板-患者信息", key: key, data: data })
          );
          await this.$store.dispatch("setWaitingPatientInfo", patientList);
          break;
      }
    },
    startTimer() {
      // 清除可能存在的旧定时器
      this.stopTimer();

      // 创建新定时器，每10秒执行一次
      this.timer = setInterval(() => {
        this.handleTimer();
      }, this.optionsInfo.switchTime * 1000);
    },
    handleTimer() {
      // 定时器执行的具体逻辑
      if (
        this.totalArr.length == 0 ||
        this.totalArr.length == 1 ||
        this.totalArr.length - 1 == this.waitIndex
      ) {
        this.waitIndex = 0;
      } else {
        this.waitIndex++;
      }
      console.log("10秒到了");
      console.log(this.waitIndex, "waitIndex");
      console.log(this.totalArr, "totalArr");
      console.log("执行定时任务:", this.getWaitingPatient);
    },
    stopTimer() {
      if (this.timer) {
        clearTimeout(this.timer);
        this.timer = null;
      }
    },
  },

  watch: {
    field: {
      handler: function (val) {
        this.widgetKey = uuid();
        this.fieldOptionsInfo = val.options;
        let key = val.options.config;
        if (!!key) {
          this.optionsInfo = val.options[key];
        }
      },
      deep: true,
      immediate: true,
    },
  },
  // 组件销毁时清除定时器
  beforeDestroy() {
    this.stopTimer();
  },
  destroyed() {
    this.unregisterFromRefList();
  },
};
</script>

<style lang="scss" scoped>
.scene-waiting-patient-widget {
  background: transparent;
  font-size: 80px;
  padding: 20px 0 0 0;
  overflow: hidden;

  .scene-waiting-patient-inside {
    height: 100%;
    display: flex;
    padding: 0 30px;
    flex-direction: row;
    align-items: start;
    align-self: center;
    justify-content: start;

    .patient-area {
      width: 100%;
      height: 100%;
      overflow: hidden;
      box-sizing: border-box;
      border-radius: 20px !important;
      display: flex;
      flex-direction: column;
      flex-grow: 1;
      background: #ffffff;
      border: 1px rgba(0, 0, 0, 0.2) solid;

      .patient-group {
        display: flex;
        flex-grow: 1;
        width: 100%;
        height: 100%;
        flex-direction: row;
        align-self: center;
        align-items: center;

        &:first-child {
          border-top: none;
        }

        &:nth-child(even) {
          background: #f8f8f9;
        }

        &:nth-child(odd) {
          background: #ffffff;
        }

        .patient-info {
          min-height: 100%;
          line-height: 100%;
          width: 100%;
          display: flex;
          align-items: center;
          align-self: center;
          justify-content: center;
          font-size: 56px;
          text-align: center;

          overflow: hidden;
          border-left: 1px rgba(0, 0, 0, 0.2) solid;

          &:first-child {
            border-left: none;
          }
          .patient-info-inside {
            @include singleEllipsis(100%);
            padding: 0 24px;
          }
        }
      }
    }
  }
}
</style>